'''
Created on 29/09/2012

@author: Christian
'''

from mercurial import ui, hg
from Repository import Repository


class RepositoryHG(Repository):
    
    def __init__(self, path, projectname):       
        super(RepositoryHG, self).__init__(path, projectname, 'HG') 
        
    def connect(self):
        u = ui.ui()
        self._repo = hg.repository(u, self.path)
    
    def getChangesAndFiles(self, changeid, repoid, fromrev, torev):
        
        print "Preparing changes from %s to %s" % (fromrev, torev)
     
        changes = []
        files = []
        counter = fromrev
        changelog = self._getChangeLog()

        if torev > len(changelog):
            torev = len(changelog)
        
        for rev in range(fromrev, torev):
            print "Processing change %s/%s" % (rev, self.getSize())
            ctx = self._repo[rev]
            changeobj = self._processChange(ctx, changeid, repoid)
            changes.append(changeobj)
            
            if len(ctx.parents()) != 2:
                files.extend(self._processChangeFiles(ctx, changeid))
                
            changeid += 1
            counter += 1
        return (changes, files)
    
    def _processChange(self, ctx, changeid, repoid):
        
        parentA = ''
        parentB = ''
        if len(ctx.parents()) == 1:
            parentA = ctx.parents()[0].hex()
        if len(ctx.parents()) == 2:
            parentA = ctx.parents()[0].hex()
            parentB = ctx.parents()[1].hex()
        
        if len(ctx.parents()) == 2:
            merge = 1
        else:
            merge = 0
            
        # USER NAME,EMAIL EXTRACTION
        pos = ctx.user().find(" <")
        if pos == -1:
            user_name = ctx.user()
            user_email = ctx.user()
        else:
            user_name = ctx.user()[0:pos]
            user_email = ctx.user()[pos + 2:len(ctx.user()) - 1]
            
        change = [changeid,
                  ctx.rev(),
                  ctx.hex(),
                  user_name,
                  user_email,
                  ctx.date()[0],
                  ctx.date()[0],
                  parentA,
                  parentB,
                  merge,
                  ctx.description(),
                  str(repoid)]
        
        return change

    def _processChangeFiles(self, ctx, changeid):
        files = []
       
        # Domain: 'E'dit, 'A'dd, 'R'emove, 'D'elete, 'U'nknown, 'I'gnore, 'C'lean
        modification = ['E', 'A', 'R', 'D', 'U', 'I', 'C']
        
        modificationcount = 0
             
        for parent in ctx.parents():
            for changefiles in self._repo.status(self._repo[parent.rev()], ctx):
                if changefiles:
                    for filename in changefiles:
                        extension = self._extractFileExtension(filename)
                        filechanged = [filename,
                                       extension,
                                       modification[modificationcount],
                                       changeid]
                        files.append(filechanged)
                modificationcount = modificationcount + 1
                    
        return files
    
    def getSize(self):
        if not self._size:
            self._size = len(self._getChangeLog()) 
        return self._size
    
    def _getChangeLog(self):
        if not  self._changelog:
            self._changelog = self._repo.changelog
        return self._changelog
